/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState, useRef, useCallback, useEffect } from 'react';
import type { ConnectState } from '@/models/connect';
import ProCard from '@ant-design/pro-card';
import OrderForm from './OrderForm';
import OrderDetail from './OrderDetail';
import Monitor from './Monitor';
import DragTable from '@/components/DragTable';
import ProTable from '@ant-design/pro-table';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import {
  getYjOrder,
  setMonitorConfig,
  getBrandList,
  addDownloadTask,
  orderCancel,
} from '@/services/operatorManagement';
import { formatBrandList } from '@/pages/OperatorManagement/YJOrder/OrderForm/utils';
import type { TableColumns } from '@/pages/OperatorManagement/types/yjorder';
import { initialValues } from './OrderForm/utils';
import { Col, Row, Button, message } from 'antd';
import { debounce } from 'lodash';
import { SettingOutlined } from '@ant-design/icons';
import { useSelector } from 'umi';
import DownloadList from './DownloadList';
import StepsLogistics from './Steps';
import styles from './index.less';
let promise: any = null;

const brandPromise = (space: string) => {
  if (!promise) {
    promise = getBrandList();
  }
  return promise.then((res: any) => {
    const { data } = res;
    return formatBrandList(data, space);
  });
};

const scrollMap = [0, 1690, 2700, 3420];

const OrderManagement: React.FC = () => {
  const { winSize } = useSelector((state: ConnectState) => state.global);
  const actionRef = useRef<ActionType>();
  const [queryConfig, setQueryConfig] = useState<{
    collect_status: any;
    channel: any;
    order_status: any;
    receive_status: any;
    help_status: any;
    pay_type: any;
    pay_status: any;
  }>();
  const [brands, setBrands] = useState<{ value: string; label: string; order_type: string }[]>();
  const [activity, setActivity] = useState(0);
  const [formData, setFormData] = useState(initialValues);
  const [detail, setDetail] = useState({});
  const [isOpened, setOpenedDetail] = useState(false);
  const [isMonitorOpened, setOpenedMonitor] = useState(false);
  const [isDownListOpened, setOpenedDownList] = useState(false);
  const [isStepsOpened, setStepsOpened] = useState(false);
  const [stepsId, setStepsId] = useState('');
  const tableReload = (cb?: () => void) => {
    const { reset } = actionRef.current || {};
    actionRef.current?.reload(false);
    if (reset) {
      reset();
    }
    if (typeof cb === 'function') {
      cb();
    }
  };
  useEffect(() => {
    brandPromise('nickname').then((data: any) => {
      setBrands(data);
    });
  }, []);
  const handleFormSubmit = (values: any) => {
    setFormData(values);
    tableReload();
  };
  const locationTableScrollLeft = (offsetLeft: number) => {
    const box = document.getElementById('kb-pro-table');
    const ele = box?.querySelector('.ant-table-body');
    if (ele) {
      ele.scrollLeft = offsetLeft;
    }
  };

  useEffect(() => {
    const box = document.getElementById('kb-pro-table');
    const ele = box?.querySelector('.ant-table-body');
    ele?.addEventListener('scroll', (res) => {
      // res.scrollLeft
      const scrollLeft = res.target?.['scrollLeft'];
      const index = scrollMap.findIndex((value, i) => {
        return scrollLeft > value && scrollLeft < (scrollMap[i + 1] || 99999);
      });
      if (index !== -1) {
        setActivity(index);
      }
    });
  }, []);

  const handleMenuChange = (index: number) => {
    locationTableScrollLeft(scrollMap[index]);
    setActivity(index);
  };
  const handleMonitorChange = (monitorData: any) => {
    setMonitorConfig(monitorData).then((res) => {
      const { code, msg } = res || {};
      const tip = code === 0 ? '设置成功' : msg;
      message.info(tip);
      setOpenedMonitor(false);
    });
  };

  const fetchTableList = (params: any, form: any) => {
    const { current: page, pageSize, ...rest } = params;
    return getYjOrder({
      page,
      page_size: pageSize,
      ...rest,
      ...form,
    }).catch((error) => {
      const { msg } = error || {};
      message.error(msg);
    });
  };

  const handleShowDetail = (data: object) => {
    setDetail(data);
    setOpenedDetail(true);
  };
  const handleAddDownloadTask = useCallback(
    debounce(() => {
      addDownloadTask(formData).then(({ success, msg }) => {
        let tip = msg;
        if (success) {
          tip = '添加下载任务成功！快去任务列表查看吧';
        }
        message.success(tip);
      });
    }),
    [formData],
  );
  const handleCancel = (d: { order_id: string; brand: string }) => {
    const { order_id, brand } = d;
    orderCancel({ order_id, brand }).then(({ msg, success }) => {
      let tip = msg;
      if (success) {
        tip = '取消成功';
      }
      message.success(tip);
      tableReload();
    });
  };
  const handleShowSteps = (id: string) => {
    setStepsId(id);
    setStepsOpened(true);
  };
  const handleOperatorClick = (type: string, d: { order_id: string; brand: string }) => {
    switch (type) {
      case 'detail':
        handleShowDetail(d);
        break;
      case 'logistics':
        const { order_id } = d;
        handleShowSteps(order_id);
        break;
      case 'cancel':
        handleCancel(d);
        break;
    }
  };
  const handleQueryChange = (data: any) => {
    setQueryConfig(data);
  };
  const columns: ProColumns<TableColumns>[] = [
    { dataIndex: 'order_id', title: '订单号', width: 150 },
    {
      dataIndex: 'channel',
      title: '订单渠道',
      width: 200,
      renderText: (value) => {
        return queryConfig ? queryConfig.channel?.[value] : '';
      },
    },
    {
      dataIndex: 'order_type',
      title: '订单类型',
      width: 90,
      renderText: (value) => {
        return brands ? brands.filter((item) => item.order_type == value)[0]?.label : '';
      },
    },
    {
      dataIndex: 'order_status',
      title: '订单状态',
      width: 90,
      renderText(value) {
        return queryConfig ? queryConfig.order_status?.[value] : '';
      },
    },
    {
      dataIndex: 'package_note',
      title: '订单备注',
      width: 150,
    },
    { dataIndex: 'order_created_at', title: '下单时间', width: 170 },
    {
      title: '预计接单时间',
      width: 210,
      renderText(d) {
        const { receive_end_time } = d;
        if (receive_end_time) {
          return `${receive_end_time}`;
        }
        return '';
      },
    },
    { dataIndex: 'receive_time', title: '实际接单时间', width: 170 },

    {
      dataIndex: 'receive_status',
      title: '接单状态',
      width: 150,
      renderText(value) {
        return queryConfig ? queryConfig.receive_status?.[value] : '';
      },
    },
    { dataIndex: 'collect_shop_name', title: '接单网点', width: 90 },
    { dataIndex: 'cancel_reason', title: '订单取消原因', width: 140 },

    {
      dataIndex: 'collect_courier_name',
      title: '接单快递员',
      width: 110,
    },
    {
      dataIndex: 'collect_courier_mobile',
      title: '快递员手机号',
      width: 120,
    },

    { dataIndex: 'shipper_uid', title: '用户ID', width: 150 },
    {
      dataIndex: 'shipper_name',
      title: '寄件人信息',
      width: 350,
      renderText: function (value: string, d: any) {
        return (
          <div>
            <p>
              {value} {d.shipper_mobile}
            </p>
            <p>
              {d.shipper_province}-{d.shipper_city}-{d.shipper_district}-{d.shipper_address}
            </p>
          </div>
        );
      },
    },
    {
      dataIndex: 'shipping_name',
      title: '收件人信息',
      width: 350,
      renderText: function (value: string, d: any) {
        return (
          <div>
            <p>
              {value} {d.shipping_mobile}
            </p>
            <p>
              {d.shipping_province}-{d.shipping_city}-{d.shipping_district}-{d.shipping_address}
            </p>
          </div>
        );
      },
    },

    {
      dataIndex: 'waybill_no',
      title: '运单号',
      width: 170,
      renderText: function (value, d: any) {
        return (
          <span
            onClick={() => handleOperatorClick('logistics', d)}
            style={{
              color: '#1E9FFF',
              fontWeight: 'bold',
              cursor: 'pointer',
            }}
          >
            {value}
          </span>
        );
      },
    },
    {
      dataIndex: 'third_party_orderid',
      title: '客户订单号',

      width: 170,
    },

    {
      title: '预计揽件时间',
      width: 210,
      renderText(d) {
        const { reserve_start_time, reserve_end_time } = d;
        if (reserve_start_time && reserve_end_time) {
          return `${reserve_start_time}~${reserve_end_time}`;
        } else if (reserve_end_time) {
          return reserve_end_time;
        }
        return '';
      },
    },
    {
      dataIndex: 'collect_date',
      title: '实际揽件时间',
      width: 100,
    },
    {
      dataIndex: 'collect_status',
      title: '揽件状态',
      width: 100,
      renderText: (value) => {
        return queryConfig ? queryConfig.collect_status?.[value] : '';
      },
    },
    {
      dataIndex: 'real_collect_courier_name',
      title: '揽件业务员',
      width: 130,
    },
    {
      dataIndex: 'real_collect_courier_mobile',
      title: '揽件业务员电话',
      width: 130,
    },
    { dataIndex: 'package_info', title: '物品类型', width: 90 },
    { dataIndex: 'product_name', title: '产品类型', width: 90 },
    { dataIndex: 'real_warrant_price', title: '保价金额', width: 90 },
    { dataIndex: 'package_weight', title: '物品重量', width: 90 },
    {
      dataIndex: 'settlement_volume',
      width: 120,
      title: '结算体积',
      renderText(value) {
        return value ? `${value}立方厘米` : '';
      },
    },
    { dataIndex: 'welfare_type', title: '福利类型', width: 90 },
    {
      dataIndex: 'help_status',
      title: '助力状态',
      width: 90,
      renderText(value) {
        return queryConfig ? queryConfig.help_status?.[value] : '';
      },
    },
    { dataIndex: 'welfare_money', title: '福利金额', width: 90 },
    { dataIndex: 'sign_status_desc', title: '签收状态', width: 90 },
    { dataIndex: 'sign_date', title: '签收时间', width: 90 },
    { dataIndex: 'charging_weight', title: '结算重量', width: 90 },
    { dataIndex: 'pay_price', title: '结算价格', width: 90 },
    {
      dataIndex: 'pay_status',
      title: '扣款状态',
      width: 90,
      renderText(value) {
        return queryConfig ? queryConfig.pay_status?.[value] : '';
      },
    },
    { dataIndex: 'pay_date', title: '扣款时间', width: 190 },
    {
      dataIndex: 'pay_type',
      title: '扣款方式',
      width: 90,
      renderText(value) {
        return queryConfig ? queryConfig.pay_type?.[value] : '';
      },
    },
    { dataIndex: 'trade_number', title: '交易流水号	', width: 100 },
    { dataIndex: 'order_number', title: '支付商户号	', width: 100 },
    {
      fixed: 'right',
      title: '操作',
      width: winSize === 'xs' || winSize === 'sm' ? 50 : 160,
      renderText: (d) => {
        const fit = { xs: 24, md: 12, lg: 12, xl: 12, xxl: 12 };
        const operatorMap = [
          {
            key: 'detail',
            title: '详情',
          },
          // { key: 'edit', title: '编辑' },
          // { key: 'log', title: '日志' },
          {
            key: 'cancel',
            title: '取消订单',
            disabled: d.order_status == '-9' || d.order_status == '8',
          },
        ];
        return (
          <Row justify='space-between'>
            {operatorMap.map((item) => {
              const { key, title, disabled } = item;
              const clsName = styles[`table-operator--${key}`];
              return (
                <Col {...fit} key={key}>
                  <Button
                    size='small'
                    onClick={handleOperatorClick.bind(null, key, d)}
                    className={clsName}
                    key={key}
                    disabled={disabled}
                  >
                    {title}
                  </Button>
                </Col>
              );
            })}
          </Row>
        );
      },
    },
  ];
  const isPhone = winSize && ['xs', 'sm'].includes(winSize);
  const toolbar = {
    title: '',
    menu: {
      items: [
        {
          key: '0',
          label: '订单信息',
        },
        {
          key: '1',
          label: '收寄件信息',
        },
        {
          key: '2',
          label: '揽件信息',
        },
        {
          key: '3',
          label: '物品及支付信息',
        },
      ],
      type: 'tab',
      activeKey: activity + '',
      onChange: handleMenuChange,
    },
    actions: (
      <Row gutter={4} justify='space-between'>
        <Col span={10} style={{ marginBottom: 10 }} xs={winSize === 'xs' ? 24 : ''}>
          <Button
            type='primary'
            size={isPhone ? 'small' : 'middle'}
            onClick={() => setOpenedDownList(true)}
          >
            查看导出列表
          </Button>
        </Col>
        <Col span={10}>
          <Button
            onClick={handleAddDownloadTask}
            type='primary'
            size={isPhone ? 'small' : 'middle'}
          >
            添加导出任务
          </Button>
        </Col>
      </Row>
    ),
  };
  return (
    <>
      <ProCard style={{ width: '100%' }}>
        <div style={{ overflow: 'hidden' }}>
          <div style={{ float: 'right', cursor: 'pointer' }} onClick={() => setOpenedMonitor(true)}>
            <SettingOutlined
              style={{
                color: '#39A2FF',
                marginRight: 5,
              }}
            />
            <span>监控设置</span>
          </div>
        </div>

        <OrderForm
          onSubmit={handleFormSubmit}
          brandPromise={brandPromise('nickname')}
          onQueryConfigChange={handleQueryChange}
        />
        <DragTable>
          <ProTable
            id='kb-pro-table'
            rowKey='order_id'
            actionRef={actionRef}
            search={false}
            options={false}
            scroll={{ y: 5780 }}
            toolbar={toolbar}
            columns={columns}
            request={(values) => fetchTableList(values, formData)}
          />
        </DragTable>
      </ProCard>
      <OrderDetail
        data={detail}
        isOpened={isOpened}
        onCancel={() => setOpenedDetail(false)}
        onOk={() => setOpenedDetail(false)}
        queryConfig={queryConfig}
        brands={brands}
      />
      <Monitor
        isOpened={isMonitorOpened}
        onCancel={() => setOpenedMonitor(false)}
        onOk={handleMonitorChange}
        brandPromise={brandPromise('name')}
      />
      <DownloadList isOpened={isDownListOpened} onCancel={() => setOpenedDownList(false)} />
      <StepsLogistics
        isOpened={isStepsOpened}
        onCancel={() => setStepsOpened(false)}
        order_id={stepsId}
      />
    </>
  );
};

export default OrderManagement;
